<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Db;
use think\Loader;
use think\exception\HttpException;
use think\Config;

class Sales extends Controller
{
//    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    protected function filter(&$map)
    {
        if ($this->request->param("realname")) {
            $map['realname'] = ["like", "%" . $this->request->param("realname") . "%"];
        }
        if ($this->request->param("idcard")) {
            $map['idcard'] = ["like", "%" . $this->request->param("idcard") . "%"];
        }
        if ($this->request->param("mobile")) {
            $map['mobile'] = ["like", "%" . $this->request->param("mobile") . "%"];
        }
    }

    //获取该批次号码段
    public function number(){
        if($this->request->isAjax()){
            $batch = $this->request->post('batch');
            $number_min = Db::name('card')->where('batch',$batch)->min('number');
            $number_max = Db::name('card')->where('batch',$batch)->max('number');
            $array_number = Db::name('card')->where('sales_id',0)->whereBetween('number',array($number_min,$number_max))->select();
            $number_plus = count($array_number);
        $res = json_encode(array('status'=>'succ','number_min'=>$number_min,'number_max'=>$number_max,'number_plus'=>$number_plus));
        exit($res);
        }
    }

    /**
     * 给销售员分配卡
     *
     */
    public function assign(){

        if($this->request->isAjax()){

            $data = $this->request->post();

            $id    = $data['id'];
            $num   = $data['num'];
            $batch = $data['batch'];
            $start_num = Db::name('card')->where('sales_id',0)->where('batch',$batch)->min('number');
            $max_num   = Db::name('card')->where('sales_id',0)->where('batch',$batch)->max('number');
            $end_num   = $start_num + $num - 1;

            //验证
            if($num < 0){
                return ajax_return_error('分配卡数不能小于0','');
            }
            if(empty($start_num)){
                return ajax_return_error('该批次已没有可分配优惠卡','');
            }
            if($end_num > $max_num){
                return ajax_return_error('分配卡数不能大于剩余卡数','');
            }

            //修改优惠卡表字段  绑定销售信息
            $res = Db::name('card')->whereBetween('number',array($start_num,$end_num))->update(['sales_id'=>$id]);

            return ajax_return_adv('发卡成功','');


        }else{
            //给销售分配卡
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $vo = $this->getModel('admin_user')->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }

            //从批次表获取所有批次
            $arr_batch = Db::name('batch')->field('batch')->select();

            $this->view->assign("vo", $vo);
            $this->view->assign('arr_batch',$arr_batch);

            return $this->view->fetch('assign');
        }
    }


    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $model = new \app\common\model\Sale();

        // 列表过滤器，生成查询Map对象
        $map = $this->search($model, [$this->fieldStatus => 1,$this->fieldIsDelete => $this::$isdelete]);

        // 特殊过滤器，后缀是方法名的
        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }

        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }

        $this->datalist($model, $map);

        return $this->view->fetch();
    }


    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $controller = $this->request->controller();
        if ($this->request->isAjax()) {
            // 插入
            $data = $this->request->except(['id']);
            $data['password'] = md5($data['password']);
            $data['create_time'] = time();
            $data['update_time'] = time();

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 写入数据   简单的直接使用db写入
            Db::startTrans();
            try {
                $model = Db::name('admin_user');
                $ret = $model->insert($data);
                //插入角色关系
                $last_id = $model->getLastInsID();
                $role_id = Db::name('admin_role')->where('name','销售')->value('id');
                $res = Db::name('admin_role_user')->insert(['role_id'=>$role_id,'user_id'=>$last_id]);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ajax_return_adv_error($e->getMessage());
            }

            return ajax_return_adv('添加成功','');
        } else {
            // 添加
            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->post();
            $data['password'] = 123456;
            $data['update_time']  = time();
//            dump($data);die;

            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 更新数据   简单的直接使用db更新
            unset($data['password']);
            Db::startTrans();
            try {
                $model = Db::name('admin_user');
                $ret = $model->where('id', $data['id'])->update($data);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ajax_return_adv_error($e->getMessage());
            }

            return ajax_return_adv("编辑成功",'');
        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $vo = $this->getModel('admin_user')->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }

            $this->view->assign("vo", $vo);

            return $this->view->fetch();
        }
    }


    /**
     * 保存排序
     */
    public function saveOrder()
    {
        $param = $this->request->param();
        if (!isset($param['sort'])) {
            return ajax_return_adv_error('缺少参数');
        }

        $model = $this->getModel();
        foreach ($param['sort'] as $id => $sort) {
            $model->where('id', $id)->update(['sort' => $sort]);
        }

        return ajax_return_adv('保存排序成功', '');
    }

    
}
